package com.koron.system.zsj.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.koron.common.core.business.todoApproval.bean.ZsjConfigInfo;
import com.koron.system.unityUser.entity.WsResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@Data
public class ZsjMessageUtil {

    // 授权码无效
    private static final int AUTH_ERROR = -1;

    // 调用成功
    private static final int SUCCESS = 1;

    // 授权码
    private static String authCode;

    @Autowired
    private ZsjConfigInfo zsjConfigInfo;


    private WsResult refreshAuthCode() {
        Map<String, Object> map = new HashMap<>();
        map.put("arg1", DigestUtils.md5Hex(zsjConfigInfo.getUsername()).toLowerCase());
        map.put("arg2", DigestUtils.md5Hex(zsjConfigInfo.getPassword()).toLowerCase());
        String string = HttpUtil.get(zsjConfigInfo.getHelloUrl(), map);
        Gson gson = new Gson();
        WsResult<String> result = gson.fromJson(string, WsResult.class);
        if (result.getCode() == SUCCESS) {
            authCode = result.getData();
        }
        return result;
    }


    /**
     * 发送短信
     *
     * @param templateID 模板id
     * @param phone      手机号码
     * @param params     参数
     * @return
     */
    public WsResult send(String templateID, String phone, String[] params) {
        // 若授权码为空，先去获取授权码
        if (StringUtils.isEmpty(authCode)) {
            WsResult result = refreshAuthCode();
            log.info("获取短信授权码：{},{},{}", result.getCode(), result.getError(), result.getMsg());
            // 若获取授权码失败，返回失败信息
            if (result.getCode() != 1) {
                return result;
            }
        }
        // 模板参数
        String templateParams = "";
        for (String s : params) {
            try {
                templateParams += "&templateParams=" + URLEncoder.encode(s, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
        }
        //请求地址
        String requestUrl = String.format("%s?auth=%s&phone=%s&templateID=%s%s", zsjConfigInfo.getSendUrl(), authCode, phone, templateID, templateParams);
        WsResult result = send(requestUrl);
        // 若授权码失效，则重新获取授权码
        if (result.getCode() == AUTH_ERROR) {
            refreshAuthCode();
            requestUrl = String.format("%s?auth=%s&phone=&s&templateID=%s%s", zsjConfigInfo.getSendUrl(), authCode, phone, templateID, templateParams);
            return send(requestUrl);
        }
        log.info("发送结果:{}", JSONUtil.toJsonStr(result));
        return result;
    }

    public WsResult send(String requestUrl) {
        String body = HttpUtil.get(requestUrl);
        WsResult<String> result = JSONUtil.toBean(body, WsResult.class);
        return result;
    }


}
